package com.hqd.ch03.v50.boot.autoconfigure.web.servlet;

import com.hqd.ch03.utils.ObjectUtils;
import com.hqd.ch03.v50.boot.autoconfigure.web.ServerProperties;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import com.hqd.ch03.v50.boot.web.server.WebServerFactoryCustomizer;
import com.hqd.ch03.v50.core.Ordered;

/**
 * Tomcat专属配置
 */
public class TomcatServletWebServerFactoryCustomizer
        implements WebServerFactoryCustomizer<TomcatServletWebServerFactory>, Ordered {

    private final ServerProperties serverProperties;

    public TomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        ServerProperties.Tomcat tomcatProperties = this.serverProperties.getTomcat();
        //配置TLD
        if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) {
            factory.getTldSkipPatterns().addAll(tomcatProperties.getAdditionalTldSkipPatterns());
        }
        //配置重定向
        if (tomcatProperties.getRedirectContextRoot() != null) {
            customizeRedirectContextRoot(factory, tomcatProperties.getRedirectContextRoot());
        }
        //配置相对路径重定向
        customizeUseRelativeRedirects(factory, tomcatProperties.isUseRelativeRedirects());
        //配置Mbean
        factory.setDisableMBeanRegistry(!tomcatProperties.getMbeanregistry().isEnabled());
    }

    private void customizeRedirectContextRoot(ConfigurableTomcatWebServerFactory factory, boolean redirectContextRoot) {
        factory.addContextCustomizers((context) -> context.setMapperContextRootRedirectEnabled(redirectContextRoot));
    }

    private void customizeUseRelativeRedirects(ConfigurableTomcatWebServerFactory factory,
                                               boolean useRelativeRedirects) {
        factory.addContextCustomizers((context) -> context.setUseRelativeRedirects(useRelativeRedirects));
    }

}

